import React, { useState } from 'react';
import {
  Card,
  Input,
  Button,
  Typography,
  Alert,
  List,
  Tag,
  Space,
  Spin
} from 'antd';
import {
  SendOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { ShieldOutlined } from '../icons/IconComponents';

const { Text, Paragraph, Title } = Typography;
const { TextArea } = Input;

/**
 * PUA检测器组件
 * 用于检测聊天内容中的PUA言论并提供应对建议
 */
const PUADetector = ({ onDetect }) => {
  const [text, setText] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);

  const handleDetect = async () => {
    if (!text.trim()) return;
    
    setLoading(true);
    try {
      // 这里只是模拟API调用
      setTimeout(() => {
        const mockResult = {
          is_pua: text.toLowerCase().includes('敏感') || text.toLowerCase().includes('想太多'),
          score: text.toLowerCase().includes('敏感') ? 0.75 : 0.4,
          risk_level: text.toLowerCase().includes('敏感') ? 'medium' : 'low',
          detected_patterns: text.toLowerCase().includes('敏感') ? [
            {
              category: 'gaslighting',
              description: '煤气灯效应，让对方怀疑自己的感受和判断',
              severity: 0.8
            }
          ] : [],
          explanation: text.toLowerCase().includes('敏感') ? 
            '该文本使用了煤气灯效应技巧，试图让对方怀疑自己的判断。' : 
            '未检测到明显的PUA内容，但建议保持警惕。',
          response_suggestions: text.toLowerCase().includes('敏感') ? [
            '我相信我的感受是真实的，这不是我想太多。',
            '请不要否认我的感受，我们应该相互尊重。',
            '我需要你尊重我的想法和感受。'
          ] : []
        };
        
        setResult(mockResult);
        if (onDetect) onDetect(mockResult);
        setLoading(false);
      }, 1000);
      
      // 实际API调用应该是这样：
      // const response = await fetch('/api/pua/detect', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ text })
      // });
      // const data = await response.json();
      // setResult(data);
      // if (onDetect) onDetect(data);
    } catch (error) {
      console.error('PUA检测失败:', error);
      setLoading(false);
    }
  };

  const getResultIcon = (isPua) => {
    if (!isPua) return <ShieldOutlined style={{ color: 'green' }} />;
    return <WarningOutlined style={{ color: 'red' }} />;
  };

  const getRiskColor = (level) => {
    switch(level) {
      case 'high': return 'red';
      case 'medium': return 'orange';
      case 'low': return 'green';
      default: return 'default';
    }
  };

  return (
    <Card
      title={
        <Space>
          <ShieldOutlined /> PUA检测
        </Space>
      }
    >
      <TextArea
        rows={4}
        placeholder="输入需要检测的文本内容..."
        value={text}
        onChange={e => setText(e.target.value)}
        style={{ marginBottom: 16 }}
      />
      
      <Button 
        type="primary" 
        icon={<SendOutlined />} 
        onClick={handleDetect}
        loading={loading}
        disabled={!text.trim()}
        block
      >
        检测PUA内容
      </Button>
      
      {loading && <Spin style={{ display: 'block', margin: '20px auto' }} />}
      
      {result && !loading && (
        <div style={{ marginTop: 16 }}>
          <Alert
            message={result.is_pua ? "检测到PUA内容" : "未检测到明显PUA内容"}
            description={result.explanation}
            type={result.is_pua ? "warning" : "success"}
            showIcon
            icon={getResultIcon(result.is_pua)}
          />
          
          {result.is_pua && (
            <>
              <div style={{ marginTop: 16 }}>
                <Title level={5}>检测到的模式:</Title>
                <List
                  dataSource={result.detected_patterns}
                  renderItem={pattern => (
                    <List.Item>
                      <Tag color={getRiskColor(result.risk_level)}>{pattern.category}</Tag>
                      <span style={{ marginLeft: 8 }}>{pattern.description}</span>
                      <span style={{ marginLeft: 8 }}>
                        严重程度: {Math.round(pattern.severity * 10)}/10
                      </span>
                    </List.Item>
                  )}
                />
              </div>
              
              <div style={{ marginTop: 16 }}>
                <Title level={5}>建议回应:</Title>
                <List
                  dataSource={result.response_suggestions}
                  renderItem={suggestion => (
                    <List.Item>
                      <Text>{suggestion}</Text>
                    </List.Item>
                  )}
                />
              </div>
            </>
          )}
        </div>
      )}
    </Card>
  );
};

export default PUADetector; 